package com.dizner.dimagepicker;

import android.app.Activity;
import android.content.Intent;

import androidx.fragment.app.Fragment;

import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.List;

public class DImagePicker {
    private WeakReference<Activity> mActivity;

    private int max = 1;
    private int resultCode = -9012231;

    private DImagePicker(Activity activity) {
        this.mActivity = new WeakReference<>(activity);
    }

    public static DImagePicker with(Activity activity) {
        return new DImagePicker(activity);
    }

    public static DImagePicker with(Fragment fragment) {
        return new DImagePicker(fragment.getActivity());
    }

    public DImagePicker max(int max) {
        this.max = max;
        return this;
    }

    public DImagePicker requestCode(int resultCode) {
        this.resultCode = resultCode;
        return this;
    }

    public void launch() {
        if (resultCode == -9012231) {
            throw new IllegalStateException("request code not set");
        }
        Intent intent = new Intent(mActivity.get(), MainPickerActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra("max", max);
        mActivity.get().startActivityForResult(intent, resultCode);
    }

    public static List<Image> outResult(Intent resultData) {
        if (resultData == null) {
            return Collections.emptyList();
        }
        String resultId = resultData.getStringExtra(MainPickerActivity.RESULT_DATA_ID);
        return MainPickerActivity.outResult(resultId);
    }
}
